import RQ from "request";
import Util from "util";

import GamePlugin from "./gamePlugin";

import PomeloLogger from "pomelo-logger";
const Logger = PomeloLogger.getLogger("HeartbeatPlugin", process.pid, __filename);

const GlobalConfig = require("../../config/global.config.json");
const ManagerConfig = require("../../config/manager.config.json");

class HeartbeatPlugin extends GamePlugin {
    constructor(gameServer) {
        super(gameServer);
        this._disconnectedTime = ManagerConfig.disconnectedTime * 1e3;
        this.socketServers = {};
    }

    configure() {}
    start() {}
    update() {
        var time = new Date();
        Object.keys(this.socketServers).forEach(kv => {
            if (time - this.socketServers[kv].time > this._disconnectedTime) {
                // Connection May Gone!~~
                var address = kv.split(":");
                var port = address[0], ip = address[1];

                // Todo: Maybe Need To Change To A More Clever Method To Auth
                var restartApi = Util.format("http://%s:%s/restartServer", ip, ManagerConfig.port);
                var postData = {"form":{
                    "username": GlobalConfig.auth.username,
                    "password": GlobalConfig.auth.password,
                    "ip": ip, "port": port
                }};

                Logger.warn("Server [ %s:%s ] Heartbeat Expired, Send Restart Post Request [ %s ] With Params [ %j ]", restartApi, postData);
                RQ.post(restartApi, postData, (err, res, data) => {
                    if (err || !res || res.statusCode !== 200) {
                        // Todo: Maybe Need To Send Email
                        Logger.error("Server Sent Restart Command [ %s ] [ %j ] Failed! ", err || !res || res.statusCode);
                    } else {
                        Logger.info("Server Sent Restart Command [ %s ] [ %j ] Feedback [ %s ]", restartApi, postData, data);
                    }
                });
            }
        });
    }
    stop() {}

    heartbeat(data) {
        if (!data.ip || !data.port || !data.processId) return;
        this.socketServers[data.port + ":" + data.ip] = {
            "processId": data.processId,
            "time": new Date()
        }
    }
}

module.exports = HeartbeatPlugin;
export default HeartbeatPlugin;
